#!/bin/zsh
set -eu

APP_DIR="${0:A:h:h}"
PAYLOAD="$APP_DIR/Resources/RealtimeHub"
MOD_ID="RealtimeHub"

show_error() {
  /usr/bin/osascript -e "display alert \"Adofai See Together\" message \"$1\" as critical buttons {\"OK\"} default button \"OK\""
  exit 1
}

show_done() {
  /usr/bin/osascript -e 'display alert "Adofai See Together installed" message "Open A Dance of Fire and Ice through Steam. The mod hosts automatically in the main hub. Press F10 for Host, Join, and future updates." buttons {"OK"} default button "OK"'
}

find_game() {
  setopt local_options null_glob
  local candidate
  local -a candidates
  candidates=(
    "$HOME/Downloads/ADOFAI/SteamLibrary/steamapps/common/A Dance of Fire and Ice"
    "$HOME/Library/Application Support/Steam/steamapps/common/A Dance of Fire and Ice"
  )

  for candidate in "${candidates[@]}"; do
    if [[ -d "$candidate/ADanceOfFireAndIce.app" ]]; then
      print -r -- "$candidate"
      return 0
    fi
  done

  for candidate in /Volumes/*/SteamLibrary/steamapps/common/'A Dance of Fire and Ice' /Volumes/*/steamapps/common/'A Dance of Fire and Ice'; do
    if [[ -d "$candidate/ADanceOfFireAndIce.app" ]]; then
      print -r -- "$candidate"
      return 0
    fi
  done

  return 1
}

GAME_ROOT="${ADOFAI_GAME_ROOT:-}"
if [[ -z "$GAME_ROOT" ]]; then
  GAME_ROOT="$(find_game || true)"
fi

if [[ -z "$GAME_ROOT" ]]; then
  GAME_ROOT="$(/usr/bin/osascript -e 'POSIX path of (choose folder with prompt "Choose the A Dance of Fire and Ice game folder")' 2>/dev/null || true)"
  GAME_ROOT="${GAME_ROOT%/}"
fi

[[ -d "$GAME_ROOT/ADanceOfFireAndIce.app" ]] || show_error "That folder does not contain ADanceOfFireAndIce.app."
[[ -f "$PAYLOAD/RealtimeHub.dll" ]] || show_error "The installer payload is incomplete. Download the ZIP again."

UMM_DLL="$GAME_ROOT/ADanceOfFireAndIce.app/Contents/Resources/Data/Managed/UnityModManager/UnityModManager.dll"
[[ -f "$UMM_DLL" ]] || show_error "Unity Mod Manager is not installed in this ADOFAI copy. Install the same mod loader used by Glitter Padlette first, then run this installer again."

MODS="$GAME_ROOT/Mods"
TARGET="$MODS/$MOD_ID"
/bin/mkdir -p "$MODS"

if [[ -d "$TARGET" ]]; then
  BACKUP="$MODS/$MOD_ID.backup.$(/bin/date +%Y%m%d-%H%M%S)"
  /bin/mv "$TARGET" "$BACKUP"
fi

/bin/cp -R "$PAYLOAD" "$TARGET"
/usr/bin/xattr -dr com.apple.quarantine "$TARGET" 2>/dev/null || true

PARAMS="$GAME_ROOT/ADanceOfFireAndIce.app/Contents/Resources/Data/Managed/UnityModManager/Params.xml"
if [[ -f "$PARAMS" ]]; then
  /usr/bin/perl -0pi -e 's{(<Hotkey>\s*<keyCode>)(?:None|F[0-9]+)(</keyCode>)}{${1}F10${2}}' "$PARAMS"
  /usr/bin/perl -0pi -e 's/(<Mod Id="RealtimeHub" Enabled=")false("\s*\/?>)/${1}true$2/g' "$PARAMS"
fi

if [[ "${ADOFAI_INSTALLER_TEST:-0}" == "1" ]]; then
  print -r -- "Installed Adofai See Together to $TARGET"
else
  show_done
fi
